package com.chenfan.mcn.job;

import com.chenfan.mcn.clients.datastore.DataStoreServer;
import com.chenfan.mcn.clients.datastore.model.RedQuotaItem;
import com.chenfan.mcn.dao.StarPlatformInfoMapper;
import com.chenfan.mcn.model.StarPlatformInfo;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author: xuxianbei
 * Date: 2021/8/5
 * Time: 16:44
 * Version:V1.0
 */
@Slf4j
public class StarPlatformInfoJob  {

    @Autowired
    private DataStoreServer dataStoreServer;

    @Autowired
    private StarPlatformInfoMapper starPlatformInfoMapper;

    /**
     * 更新红人平台信息
     */
    @XxlJob(value = "updateStarPlatformInfo")
    public ReturnT<String> updateStarPlatformInfo(String param) {
        List<StarPlatformInfo> starPlatformInfoList = starPlatformInfoMapper.selectAll();
        starPlatformInfoList.forEach(starPlatformInfo -> {
            try {
                List<RedQuotaItem> redQuotaItems = dataStoreServer.getDcMcnQuota(starPlatformInfo.getPlatformId(), starPlatformInfo.getStarPlatformId());
                if (!CollectionUtils.isEmpty(redQuotaItems)) {
                    RedQuotaItem redQuotaItem = redQuotaItems.get(0);
                    int sum = (redQuotaItem.getCommentnum() == null ? 0 : redQuotaItem.getCommentnum()) +
                            (redQuotaItem.getSharenum() == null ? 0 : redQuotaItem.getSharenum()) +
                            (redQuotaItem.getLikednum() == null ? 0 : redQuotaItem.getLikednum());
                    starPlatformInfo.setInteractiveQuantity(BigDecimal.valueOf(sum));
                    starPlatformInfo.setGraphicReadingQuantity(
                            divTenThousand(BigDecimal.valueOf(redQuotaItem.getCollectednum() == null ? 0 : redQuotaItem.getCollectednum())));
                    starPlatformInfo.setVideoReadingQuantity(
                            divTenThousand(BigDecimal.valueOf(redQuotaItem.getViewnum() == null ? 0 : redQuotaItem.getViewnum())));
                    starPlatformInfo.setVideoPlayQuantity(
                            divTenThousand(BigDecimal.valueOf(redQuotaItem.getViewnum() == null ? 0 : redQuotaItem.getViewnum())));
                    starPlatformInfoMapper.updateById(starPlatformInfo);
                }
            } catch (Exception e) {
                log.error("红人信息更新失败：", e);
                XxlJobLogger.log(e);
                XxlJobLogger.log(starPlatformInfo.toString());
            }
        });
        return ReturnT.SUCCESS;
    }

    private static BigDecimal divTenThousand(BigDecimal value) {
        return value.divide(BigDecimal.valueOf(10000), 2, BigDecimal.ROUND_HALF_UP);
    }
}
